FOR ... NEXT
FOR loops eliminate a common programming error that occurs with DO loops, namely failure
to update a loop variable or test variable.
If INC byteOffset is left out of the preceding example, the 1st byte of testString$ is added to hash indefinitely, instead of each byte being added once as intended. The following example performs the same function, except the inner DO loop is replaced by a FOR loop. byteOffset is incremented automatically by the NEXT statement, avoiding the possibility of an inadvertent endless loop.
FOR ... NEXT example
FUNCTION PlayTheHashGame ()
$BYTE0 = BITFIELD (8, 0)
'
DO
testString$ = INLINE$("Compute hash for string ===>> ")
hash = 0
IF testString$ THEN EXIT DO
FOR byteOffset = 0 TO LEN (testString$) - 1
testByte = testString${byteOffset}
hash = hash + testByte
NEXT byteOffset
hash = hash{$BYTE0}
PRINT "The hash for "; testString$; " is: ";
HEXX$(hash, 2)
LOOP
PRINT "***** DONE *****"
END FUNCTION
FOR options
The order of execution in FOR loops is altered when any of the following statements
execute:
DO FOR - continue at the top (the FOR)
DO NEXT - continue at the bottom (the NEXT)
EXIT FOR - exit (past the NEXT)
The following example illustrates these options:
FOR i = j TO k STEP x '
Shuffle (@x, @y, @z) ' new values for x, y, z
PRINT "Start FOR" '
IF x THEN DO NEXT ' jump down to NEXT statement
PRINT "x = 0" '
IF y THEN DO FOR ' jump up to FOR
statement
PRINT "y = 0"
'
IF z THEN EXIT FOR ' jump past NEXT statement
PRINT "z = 0"
'
NEXT i '